﻿using ProjectFootball.MVC.Foundation.Repositories;
using ProjectFootball.MVC.Foundation.ResourceLibrary;
using System;
using System.Linq;
using System.Security.Principal;

namespace ProjectFootball.MVC.Models.EntityFramework.Entities
{
    public static class EntityExtensions
    {
        public static bool CanView(this IApprovableEntity entity, IPrincipal user)
        {
            if ((entity.IsPublic && entity.IsApproved) || entity.IsOwner(user))
                return true;

            if (entity.CanApprove(user))
                return true;

            return false;
        }

        public static bool CanEdit(this IApprovableEntity entity, IPrincipal user)
        {
            if (entity.IsPublic)
            {
                if (user.IsApprover())
                    return true;
                else
                {
                    if (entity.IsOwner(user))
                        return true;
                }
            }
            else if (entity.IsOwner(user))
                    return true;

            return false;
        }

        public static bool CanApprove(this IApprovableEntity entity, IPrincipal user)
        {
            return !entity.IsApproved && user.IsApprover();
        }

        public static bool CanDelete(this IApprovableEntity entity, IPrincipal user)
        {
            return user.IsApprover() || entity.IsOwner(user);
        }

        public static bool IsOwner(this IApprovableEntity entity, IPrincipal user)
        {
            return entity.OwnerUserId == user.GetUserId();
        }

        public static void MarkForDeletion(this IApprovableEntity entity)
        {
            entity.IsMarkedForDeletion = true;
        }

        public static DbType GetEditorDbTypeForEdit(this IApprovableEntity entity, IPrincipal user)
        {
            return entity.IsPublic ? user.IsApprover() ? DbType.EditedPublic : DbType.EditedUnapproved : DbType.EditedPrivate;
        }
    }
}